<template>
  <el-dialog @close="handleClose" :close-on-click-modal="false" :destroy-on-close="true" :visible="showSetting"
    append-to-body title="排班信息" width="1000px">
    <div class="calendar">
      <div class="calendar-container">
        <el-calendar v-model="value" @input="handleCalendarChange">
          <template #dateCell="{ date, data }">
            <div class="custom-calendar-cell">
              {{ data.day.split('-').slice(1).join('-') }}{{ isSpecialDate(date) ? '✔️' : '' }}
              <div v-if="isSpecialDate(date)" class="special-date">
                <p>已排班</p>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
      <div class="time-container">
        <header>选择时间点({{ formatDateToYYYYMMDD(value) }})</header>
        <div class="time-slots">
          <div @click="handleTime(time)" v-for="time in timeSlots" :key="time"
            :class="toggleArray(time) ? 'time-slot' : 'time-slot-select'">
            {{ time }}
          </div>
        </div>
        <div v-if="!isPastDate(value)" style="display: flex;justify-content: end;padding:  20px;">
          <el-button type="success" @click="submitExpert(formatDateToYYYYMMDD(value),1)">提交排班</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
const ORIGINAL_THEME = '#409EFF' // default color
import { expertSchedule, expertScheduleList } from "@/api/expert/expert";
export default {
  props: ['showSetting', 'expertId'],
  data() {
    return {
      timeSlots: [          // 时间点
        '09:00-10:00',
        '10:00-11:00',
        '11:00-12:00',
        '13:00-14:00',
        '14:00-15:00',
        '15:00-16:00',
        '16:00-17:00'
      ],
      selectDateTime: [],//选中的时间
      selectDateTimeCopy: [],
      value: new Date(),
      array: [
        // {
        //   id: 1,
        //   data: '2025-06-04',
        //   isPai: true
        // },
        // {
        //   id: 2,
        //   data: '2025-06-09',
        //   isPai: true
        // }
      ],
      currentMonth: null
    }
  },
  mounted() {
    // 初始化时查询当天排班
    if (this.expertId) {
      this.fetchScheduleData(this.formatDateToYYYYMMDD(this.value));
      this.fetchMonthSchedule(new Date());
    }
  },
  computed: {
  },
  watch: {
    expertId(newVal) {
      if (newVal && this.showSetting) {
        this.fetchScheduleData(this.formatDateToYYYYMMDD(this.value));
      }
    },
    showSetting(newVal) {
      if (newVal && this.expertId) {
        this.value = new Date();
        this.fetchScheduleData(this.formatDateToYYYYMMDD(this.value));
        this.fetchMonthSchedule(new Date());
      }
    },
    value: {
      async handler(newVal, oldVal) {
        if (this.loading || !this.expertId) return;

        // 提交旧日期的排班
        if (oldVal) {
          const oldDate = this.formatDateToYYYYMMDD(oldVal);
          await this.submitCurrentSchedule(oldDate);
        }

        // 加载新日期的数据
        this.fetchScheduleData(this.formatDateToYYYYMMDD(newVal));
      },
      deep: true
    }
    // value: {
    //   handler(newVal) {
    //     // 日期变化时查询新日期的排班
    //     this.fetchScheduleData(this.formatDateToYYYYMMDD(newVal));
    //   },
    //   deep: true
    // }
  },
  created() {
  },
  methods: {
    // 处理月份切换事件
    handleMonthChange(date) {
      console.log(date, 'datedate')
      this.fetchMonthSchedule(date);
    },
    handleCalendarChange(date) {
      const year = date.getFullYear();
      const currentMonth = date.getMonth() + 1;
      let currentDate = `${year}-${currentMonth.toString().padStart(2, '0')}`;
      this.array = []
      expertScheduleList({
        expertId: this.expertId,
        scheduleMonth: currentDate
      }).then(res => {
        const scheduleDateList = res.rows.map(item => item.scheduleDate);
        const uniqueArray = [...new Set(scheduleDateList)];
        this.array = uniqueArray.map(item => ({
          id: item,
          data: item,
          isPai: true
        }));
      }).catch(error => {
        console.error('获取月排班信息失败:', error);
      });
    },
    // 获取整个月的排班数据
    fetchMonthSchedule(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.currentMonth = `${year}-${month.toString().padStart(2, '0')}`;

      expertScheduleList({
        expertId: this.expertId,
        scheduleMonth: this.currentMonth
      }).then(res => {
        const scheduleDateList = res.rows.map(item => item.scheduleDate);
        const uniqueArray = [...new Set(scheduleDateList)];
        this.array = uniqueArray.map(item => ({
          id: item,
          data: item,
          isPai: true
        }));
      }).catch(error => {
        console.error('获取月排班信息失败:', error);
      });
    },
    // 新增方法：提交当前日期的排班
    async submitCurrentSchedule(date) {
      const currentSchedule = this.selectDateTimeCopy.find(item => item.date === date);
      if (!currentSchedule || currentSchedule.selectDateTime.length === 0) return;
      try {
        await this.submitExpert(date);
        this.array.push({
          id: currentSchedule.date,
          data: currentSchedule.date,
          isPai: true
        })

      } catch (error) {
        console.error('自动保存失败:', error);
        this.$modal.msgError("自动保存失败");
      }
    },
    getDetail(id) {
      this.value = new Date();
      expertScheduleList({
        expertId: id
      }).then(res => {
        const scheduleDateList = res.rows.map(item => item.scheduleDate)
        const uniqueArray = [...new Set(scheduleDateList)];
        this.array = []
        uniqueArray.forEach(item => {
          this.array.push({
            id: item,
            data: item,
            isPai: true
          });
        })
      })
    },
    isPastDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 清除时间部分，只比较日期
      return new Date(date) < today;
    },
    async fetchScheduleData(date) {
      if (this.loading) return;
      this.loading = true;

      try {
        const res = await expertScheduleList({
          expertId: this.expertId,
          scheduleDate: date
        });

        // 清空当前日期的旧数据
        this.selectDateTimeCopy = this.selectDateTimeCopy.filter(item => item.date !== date);

        // 处理新数据
        if (res.rows && res.rows.length > 0) {
          const timeSlots = res.rows.map(item => `${item.startScheduleTime}-${item.endScheduleTime}`);

          this.selectDateTimeCopy.push({
            date: date,
            selectDateTime: timeSlots
          });

          this.selectDateTime = timeSlots;
        } else {
          this.selectDateTimeCopy.push({
            date: date,
            selectDateTime: []
          });
          this.selectDateTime = [];
        }
      } catch (error) {
        console.error('获取排班信息失败:', error);
      } finally {
        this.loading = false;
      }
    },
    // 获取排班数据
    // fetchScheduleData(date) {
    //   if (this.loading) return;
    //   this.loading = true;
    //   expertScheduleList({
    //     expertId: this.expertId,
    //     scheduleDate: date
    //   }).then(res => {
    //     this.selectDateTimeCopy = this.selectDateTimeCopy.filter(item => item.date !== date);
    //     if (res.rows && res.rows.length > 0) {
    //       const timeSlots = res.rows.map(item => `${item.startScheduleTime}-${item.endScheduleTime}`);
    //       this.selectDateTimeCopy.push({
    //         date: date,
    //         selectDateTime: timeSlots
    //       });

    //       this.selectDateTime = timeSlots;
    //     } else {
    //       this.selectDateTimeCopy.push({
    //         date: date,
    //         selectDateTime: []
    //       });
    //       this.selectDateTime = [];
    //     }
    //   }).catch(error => {
    //     console.error('获取排班信息失败:', error);
    //   }).finally(() => {
    //     this.loading = false;
    //   });
    // },
    // submitExpert(value) {
    //   let allDate = [];
    //   let expertScheduleList = [];

    //   this.selectDateTimeCopy.forEach(item => {
    //     if (value == item.date) {
    //       allDate = item.selectDateTime;
    //     }
    //   });
    //   if (allDate.length == 0) {
    //     this.$modal.msgSuccess("请先选择排班");
    //     return;
    //   }
    //   allDate.forEach(item => {
    //     expertScheduleList.push({
    //       startScheduleTime: item.split('-')[0],
    //       endScheduleTime: item.split('-')[1]
    //     });
    //   });

    //   expertSchedule([
    //     {
    //       expertId: this.expertId,
    //       scheduleDate: value,
    //       expertScheduleList: expertScheduleList
    //     }
    //   ]).then(res => {
    //     this.$modal.msgSuccess("设置成功");
    //     // 提交成功后刷新当前日期的排班状态
    //     this.fetchScheduleData(value);
    //   });
    // },

    // 修改原有的 submitExpert 方法，使其返回 Promise
    submitExpert(value,status) {
      return new Promise((resolve, reject) => {
        let allDate = [];
        let expertScheduleList = [];

        this.selectDateTimeCopy.forEach(item => {
          if (value == item.date) {
            allDate = item.selectDateTime;
          }
        });

        if (allDate.length == 0) {
          resolve();
          return;
        }

        allDate.forEach(item => {
          expertScheduleList.push({
            startScheduleTime: item.split('-')[0],
            endScheduleTime: item.split('-')[1]
          });
        });

        expertSchedule([
          {
            expertId: this.expertId,
            scheduleDate: value,
            expertScheduleList: expertScheduleList
          }
        ]).then(res => {
          if(status){this.$modal.msgSuccess("保存成功");}
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },
    isSpecialDate(date) {
      const day = this.formatDateToYYYYMMDD(date);
      return this.isSave(day);
    },
    handleTime(time) {
      this.selectDateTime = this.toggleArrayElement(this.selectDateTime, time);
      this.selectDateTimeCopy.forEach((i) => {
        if (i.date === this.formatDateToYYYYMMDD(this.value)) {
          i.selectDateTime = [...this.selectDateTime];
        }
      });
    },
    toggleArrayElement(array, element) {
      const index = array.indexOf(element);
      if (index === -1) {
        return [...array, element];
      } else {
        return array.filter((item, i) => i !== index);
      }
    },
    toggleArray(element) {
      const index = this.selectDateTime.indexOf(element);
      return index === -1;
    },
    handleClose() {
      this.$emit('closeDialog', false);
    },
    formatDateToYYYYMMDD(dateString) {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date string');
      }
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    },
    isSave(e) {
      return this.array.some(item => item.data === e);
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-calendar-table td.is-selected {
  background-color: #a6cff1 !important;
}

.calendar {
  width: 100%;
  max-height: 700px;
  overflow-y: auto;
  display: flex;
}

.calendar-container {
  font-family: Arial, sans-serif;
  max-width: 600px;
  padding: 10px 20px;
}

.time-container {
  width: calc(100% - 600px);
  padding: 10px 20px;

  header {
    padding: 12px 20px;
    height: 53px;
    line-height: 53px;
    border-bottom: 1px solid #dfe6ec;
  }
}

.time-slots {
  margin-top: 35px;
  padding-top: 20px;
}

.time-slot {
  padding: 10px;
  margin-bottom: 8px;
  background-color: #f5f5f5;
  color: #707070;
  border-radius: 4px;
  cursor: pointer;
}

.time-slot-select {
  padding: 10px;
  margin-bottom: 8px;
  background-color: #1890ff;
  color: #FFFFFF;
  border-radius: 4px;
  cursor: pointer;
}
</style>
